<template>
  <div>
    <!--
      必备
        action 上传地址必填, 现在没有放个 # 即可
        file-list 管理文件数组, 必备
      样式
        list-type 控制显示的样式, 给个 picture-card
        :class 可以绑定动态类名, 根据图片存在与否决定是否显示上传图标

      其他钩子
        on-preview 绑定后会出现放大镜, 点击弹窗逻辑需要自己实现
     -->
    <el-upload
      ref="upload"

      action="#"
      :file-list="fileList"
      :class="{disable: fileList.length>0}"
      list-type="picture-card"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
    >

      <i class="el-icon-plus " />
    </el-upload>

    <el-progress
      v-if="isShowProgress"
      :text-inside="true"

      :stroke-width="26"
      :percentage="percentage"
      style="width: 146px"
    />
    <el-dialog title="预览" width="80%" :visible="isShowDialog" @close="isShowDialog=false">
      <el-row type="flex" justify="center">
        <img v-fixImg="require(`@/assets/common/1.jpg`)" :src="imgUrl" alt="">
      </el-row>

    </el-dialog>
  </div>
</template>

<script>

import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDkJbcNsABvOaU7SWJo31i8HAm7BzVkhOo',
  SecretKey: 'A3f04rMbZHitmOjoc9PO6XhbFcaIjtmO'
})
export default {
  data() {
    return {
      fileList: [],
      imgUrl: '',
      isShowDialog: false,
      percentage: 0,
      isShowProgress: false
    }
  },

  methods: {

    // 绑定url
    onPreview(file) {
      this.imgUrl = file.url
      this.isShowDialog = true
    },

    // 由于没有双向绑定, 删除图片this.fileList会遗留
    // 这个函数就把最新列表传进来, 覆盖即可
    onRemove(FILE, fileList) {
      this.fileList = fileList
    },
    // 上传
    onChange(FILE, fileList) {
      this.fileList = fileList
    },

    httpRequest(params) {
      // 此处替代默认上传行为

      this.isShowProgress = true
      cos.putObject({

        Bucket: '123123-1309020520',
        Region: 'ap-nanjing', // 地域
        Key: params.file.name, // 文件名
        Body: params.file, // 要上传的文件对象
        StorageClass: 'STANDARD', // 上传的模式类型 直接默认 标准模式即可
        onProgress: (progressData) => {
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (!err) {
          const url = this.fileList[0].url = 'http://' + data.Location // url网址
          this.$emit('picUrl', url)

          // this.fileList[0].url = 'http://' + data.Location // url网址
        }
        setTimeout(() => {
          this.isShowProgress = false
        }, 1000)
      })
    },

    beforeUpload(file) {
      const maxSize = 2 * 1024 * 1024

      if (file.size > maxSize) {
        this.$message.warning('文件太大无法上传')
        return false
      }

      const whitelist = ['image/jpeg', 'image/png', 'image/gif']

      if (!whitelist.includes(file.type)) {
        this.$message.warning('只支持jpg/png格式')
        return false
      }
    }

  }

}
</script>

<style lang="scss" scoped>
.disable {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
